package com.software.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.software.bean.BannerBean;
import com.software.bean.CategoryBean;
import com.software.dto.BannerDto;
import com.software.mapper.BannerMapper;
import com.software.mapper.CategoryMapper;
import com.software.service.BannerService;
import com.software.utils.AssertUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wyj
 * @since 2024-03-02
 */
@Service
public class BannerServiceImpl extends ServiceImpl<BannerMapper, BannerBean> implements BannerService {


    @Autowired
    private BannerMapper bannerMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    // banner 分页
    @Override
    public IPage<BannerBean> queryAllBannerPagination(Page<BannerBean> page) {
        return bannerMapper.queryAllBannerPagination(page);
    }

    @Override
    public int deleteBannerById(Integer id) {
        AssertUtil.isTrue(id == null || id == 0, "参数错误");
        BannerBean bannerBean = bannerMapper.selectById(id);
        AssertUtil.isTrue(bannerBean == null, "返回值异常");
        bannerBean.setStatus(0);
        // 删除文件
        Boolean result = deleteImage(bannerBean);
        AssertUtil.isTrue(result == false, "文件操作异常了");
        int i = bannerMapper.updateById(bannerBean);
        return i == 1 ? 1 : 0;
    }


    @Override
    public List<BannerBean> listBySort() {
        QueryWrapper<BannerBean> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        queryWrapper.orderByDesc("sort");
        List<BannerBean> bannerBeanList = bannerMapper.selectList(queryWrapper);
        AssertUtil.isTrue(bannerBeanList.size() == 0, "返回异常");

        return bannerBeanList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addBanner(BannerDto bannerDto) {
        // 参数校验
        AssertUtil.isTrue(bannerDto.getFile() == null, "图片为空");
        AssertUtil.isTrue(bannerDto.getSort() == 0, "排序值异常");
        AssertUtil.isTrue(StringUtils.isEmpty(bannerDto.getImgName()), "图片名称为空");
        AssertUtil.isTrue(bannerDto.getCategoryId() == null, "指向分类异常");
        CategoryBean categoryBean = categoryMapper.selectById(bannerDto.getCategoryId());
        AssertUtil.isTrue(categoryBean == null, "分类不存在");
        //初始化参数
        BannerBean bannerBean = new BannerBean();
        bannerBean.setStatus(1);
        bannerBean.setCreateTime(new Date());
        bannerBean.setUpdateTime(new Date());
        bannerBean.setCategoryId(bannerDto.getCategoryId());
        bannerBean.setSort(bannerDto.getSort());
        bannerBean.setImgName(bannerDto.getImgName());
        String imgUrl = saveImage(bannerDto.getFile());
        bannerBean.setBannerUrl(imgUrl);

        int insert = bannerMapper.insert(bannerBean);
        return insert == 1 ? 1 : 0;
    }


    // 保存图片
    private String saveImage(MultipartFile multipartFile) {
        String realPath = "E:/img";
        // 图片名称
        String fileName = UUID.randomUUID().toString().replace("-", "");
        //图片url
        String imgUrl = "http://localhost:8082/file/" + fileName + ".jpg";
        String filePath = realPath + "/" + fileName + ".jpg";
        MultipartFile file = multipartFile;

        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return imgUrl;

    }

    @Override
    public BannerBean getBannerById(Integer id) {
        AssertUtil.isTrue(id == null, "参数异常");
        BannerBean bannerBean = bannerMapper.selectById(id);
        AssertUtil.isTrue(bannerBean == null, "返回值异常");
        return bannerBean;
    }

    @Override
    public Integer updateBanner(BannerDto editBannerDto) {
        String imgUrl = null;
        // 参数校验
        AssertUtil.isTrue(editBannerDto.getId() == null, "参数异常");
        AssertUtil.isTrue(editBannerDto.getSort() == 0, "参数异常");
        AssertUtil.isTrue(StringUtils.isEmpty(editBannerDto.getImgName()), "参数异常");
        AssertUtil.isTrue(editBannerDto.getCategoryId() == null, "指向分类不能为空");
        CategoryBean categoryBean = categoryMapper.selectById(editBannerDto.getCategoryId());
        AssertUtil.isTrue(categoryBean == null, "指向分类不存在");
        if (editBannerDto.getIsChangeImage() == true) {
            AssertUtil.isTrue(editBannerDto.getFile() == null, "参数异常file");
        }
        // 根据id 查是否有这条记录
        BannerBean bannerBean = bannerMapper.selectById(editBannerDto.getId());
        AssertUtil.isTrue(bannerBean == null, "返回值异常");
        // 先删除文件
        if (editBannerDto.getIsChangeImage() == true) {
            Boolean deleteImage = deleteImage(bannerBean);
            AssertUtil.isTrue(deleteImage == false, "文件操作异常");
            //在添加文件
            imgUrl = saveImage(editBannerDto.getFile());
        }

        // 更新
        BannerBean update = new BannerBean();
        update.setId(bannerBean.getId());
        update.setUpdateTime(new Date());
        update.setImgName(editBannerDto.getImgName());
        if (editBannerDto.getIsChangeImage() == true) {
            update.setBannerUrl(imgUrl);
        } else {
            update.setBannerUrl(null);

        }
        update.setSort(editBannerDto.getSort());
        update.setCategoryId(editBannerDto.getCategoryId());
        int i = bannerMapper.updateById(update);

        return i == 1 ? 1 : 0;
    }

    // 删除图片
    private Boolean deleteImage(BannerBean bannerBean) {
        String bannerUrl = bannerBean.getBannerUrl();
        //        String str= url.substring(url.lastIndexOf("/")+1);
        String endUrl = bannerUrl.substring(bannerUrl.lastIndexOf("/") + 1);
        String realPath = "E:/img";
        String filePath = realPath + "/" + endUrl;
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        } else {
            return false;
        }
        return true;
    }


}
